package com.yanqu.road.server.manger.drugstore;

import com.yanqu.road.entity.config.building.BuildingInfo;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.drugstore.DrugHardCaseRecordData;
import com.yanqu.road.entity.drugstore.DrugHardDispenseRankData;
import com.yanqu.road.entity.drugstore.DrugOrderNeed;
import com.yanqu.road.entity.drugstore.DrugStoreTeach;
import com.yanqu.road.entity.drugstore.config.DrugStoreDrugUpgradeInfo;
import com.yanqu.road.entity.drugstore.config.DrugStorePrescriptionInfo;
import com.yanqu.road.entity.enums.eGoodsType;
import com.yanqu.road.entity.player.UserBuilding;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.logic.bussiness.player.DrugStoreBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.drugstore.DrugStoreProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.drugstore.DrugStoreModule;
import com.yanqu.road.server.manger.config.BuildingMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DrugStoreMgr extends TempMgr {

    /**
     *  配方榜
     */
    public static Map<Integer, DrugHardDispenseRankData> dispenseMap = new ConcurrentHashMap<>();

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        dispenseMap = DrugStoreBussiness.getDrugHardDispenseRankDataMap();
        return true;
    }

    @Override
    public boolean save() {
        for (DrugHardDispenseRankData item : dispenseMap.values()){
            if(item.isUpdateOption()){
                DrugStoreBussiness.updateDrugHardDispenseRankData(item);
            }else if(item.isInsertOption()){
                DrugStoreBussiness.addDrugHardDispenseRankData(item);
            }
        }
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    public static long getOffLineLimitTime() {
        return GameConfig.DRUGSTORE_OFFLINE_BEGIN_TIME * 1000;
    }

    /**
     * 生成处方的药材需求单
     */
    public static List<DrugOrderNeed> generateOrderDrugNeed(int chuFang) {
        List<DrugOrderNeed> result = new ArrayList<>();
        DrugStorePrescriptionInfo prescriptionInfo = DrugStoreConfigMgr.getDrugStorePrescriptionInfo(chuFang);
        if(prescriptionInfo != null){
            List<String> makeStringList = StringUtils.stringToStringList(prescriptionInfo.getMake(), "\\|");
            if(makeStringList.size() > 0){
                List<String> makeItemStringList = StringUtils.stringToStringList(makeStringList.get(0), ";");
                for (String makeItemString : makeItemStringList) {
                    List<Integer> itemList = StringUtils.stringToIntegerList(makeItemString, "=");
                    DrugOrderNeed need = new DrugOrderNeed();
                    need.setItemId(itemList.get(0));
                    need.setNeedNum(itemList.get(1));
                    result.add(need);
                }
            }
        }
        return result;
    }

    /**
     * 离线后处理单个病人的速率
     * @return 返回秒
     */
    public static int getCuteTimePerPatientOffLine(int queueLen){
        int second = 0;
        List<String> rangeList = StringUtils.stringToStringList(GameConfig.DRUGSTORE_OFFLINE_DEAL_TIME, "\\|");
        for (String rangeStr : rangeList) {
            List<Integer> list = StringUtils.stringToIntegerList(rangeStr, ";");
            if(list.size() == 3){
                if(queueLen >= list.get(0) && queueLen <= list.get(1)){
                    second = list.get(2);
                }
            }
        }
        return second;
    }

    /**
     * 获取解锁的药材
     */
    public static List<Integer> getUnLockDrug(int storeLv){
        List<Integer> result = new ArrayList<>();
        for (Map.Entry<Integer, GoodsInfo> entry : GoodsMgr.getGoodsMap().entrySet()) {
            if(entry.getValue().getType() != eGoodsType.DrugStoreHerbs.getValue()){
                continue;
            }
            if(entry.getValue().getParamList().get(2).intValue() == storeLv){
                result.add(entry.getValue().getGoodsId());
            }
        }
        return result;
    }

    /**
     * 获取行走到桌子的时间
     */
    public static int getWalkTimeToDrugTable(int tableId){
        List<Integer> list = StringUtils.stringToIntegerList(GameConfig.DRUGSTORE_ANI_TIME_WALK, "\\|");
        if(tableId > list.size()){
            return 0;
        }
        return list.get(tableId - 1);
    }

    /**
     * 获取药方制作难度加成
     */
    public static int getChuFangMakeDifficultAdd(int difficult){
        List<Integer> list = StringUtils.stringToIntegerList(GameConfig.DRUGSTORE_PRESCRIPTION_LV_ADD, "\\|");
        if(list.size() == 0){
            return 0;
        }
        if(difficult > list.size() - 1){
            return list.get(list.size() - 1);
        }
        return list.get(difficult - 1);
    }

    /**
     * 工艺对伙计的加成
     * @param teachList
     * @param userBuilding
     * @return
     */
    public static int getTechnologyAdd(List<DrugStoreTeach> teachList, UserBuilding userBuilding) {
        int addition = 0;
        BuildingInfo buildingInfo = BuildingMgr.getBuildingInfo(userBuilding.getBuildingId());
        if(buildingInfo == null){
            return addition;
        }
        for (int i = 0; i < teachList.size(); i++) {
            DrugStoreTeach teach = teachList.get(i);
            DrugStoreDrugUpgradeInfo upgradeInfo = DrugStoreConfigMgr.getDrugStoreDrugUpgradeInfo(teach.getId(), teach.getLv());
            if(upgradeInfo != null){
                for (int skillId : upgradeInfo.getSkillList()) {
                    SkillInfo skillInfo = SkillMgr.getSkillInfo(skillId);
                    if (skillInfo != null) {
                        if(skillInfo.getParamList().get(2) == 0 || skillInfo.getParamList().get(2) == buildingInfo.getOccupation()){
                            addition += SkillMgr.getSkillAddition(skillInfo, teach.getLv());
                        }
                    }
                }
            }
        }
        return addition;
    }

    /**
     * 查看排行榜(配方榜)
     */
    public static DrugStoreProto.DrugStoreGetRankRespMsg.Builder getHardCaseRank(){
        DrugStoreProto.DrugStoreGetRankRespMsg.Builder builder = DrugStoreProto.DrugStoreGetRankRespMsg.newBuilder();
        for (DrugHardDispenseRankData item : dispenseMap.values()){
            builder.addListRank(builderDrugStoreDispenseRank(item));
        }
        builder.setRet(0);
        return builder;
    }

    /**
     * 领取排行榜奖励(配方榜)
     * @param player
     * @param caseId
     */
    public static DrugStoreProto.DrugStoreReceiveRankRespMsg.Builder receiveRank(GamePlayer player, int caseId){
        DrugStoreProto.DrugStoreReceiveRankRespMsg.Builder builder = DrugStoreProto.DrugStoreReceiveRankRespMsg.newBuilder();
        if(!dispenseMap.containsKey(caseId)){
            builder.setRet(GameErrorCode.E_DRUG_STORE_NO_FULL_ANSWER);
            return builder;
        }
        return player.getModule(DrugStoreModule.class).receiveRank(caseId);
    }

    /**
     * 加入满分配方榜
     * @param record
     */
    public static synchronized void addDispenseList(DrugHardCaseRecordData record){
        if(dispenseMap.containsKey(record.getCaseId())){
            return;
        }
        DrugHardDispenseRankData dispenseRankData = new DrugHardDispenseRankData();
        dispenseRankData.setCaseId(record.getCaseId());
        dispenseRankData.setUserId(record.getUserId());
        dispenseRankData.setTime(record.getTime());
        dispenseRankData.setInsertOption();
        dispenseMap.put(record.getCaseId(), dispenseRankData);
        // 同步给玩家
        synDrugStoreDispenseRankCaseList(0);
    }

    /**
     * 同步配方榜的病例集合
     * @param userId
     */
    public static void synDrugStoreDispenseRankCaseList(long userId){
        DrugStoreProto.SynDrugStoreDispenseRankCaseListRespMsg.Builder builder = DrugStoreProto.SynDrugStoreDispenseRankCaseListRespMsg.newBuilder();
        builder.addAllCaseIdList(dispenseMap.keySet());
        if(userId == 0){
            List<GamePlayer> onLinePlayer = GamePlayerMgr.getAllOnlinePlayer();
            for (GamePlayer player : onLinePlayer) {
                player.sendPacket(Protocol.U_DRUG_STORE_HARD_CASE_SYN_DISPENSE_RANK_CASE_LIST, builder);
            }
        }else {
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if(player != null){
                player.sendPacket(Protocol.U_DRUG_STORE_HARD_CASE_SYN_DISPENSE_RANK_CASE_LIST, builder);
            }
        }
    }


    public static DrugStoreProto.DrugStoreDispenseRank.Builder builderDrugStoreDispenseRank(DrugHardDispenseRankData drugHardDispenseRankData){
        DrugStoreProto.DrugStoreDispenseRank.Builder builder = DrugStoreProto.DrugStoreDispenseRank.newBuilder();
        builder.setCaseId(drugHardDispenseRankData.getCaseId());
        builder.setUserId(drugHardDispenseRankData.getUserId());
        builder.setTime(drugHardDispenseRankData.getTime());
        UserInfo userInfo = UserMgr.getUserInfo(drugHardDispenseRankData.getUserId());
        if(userInfo != null){
            builder.setPlayerInfo(PlayerPb.parsePlayerBaseTempMsg(userInfo));
        }
        return builder;
    }

}
